import { Component } from '@angular/core';
import { NzModalService, NzModalRef, NzNotificationService } from 'ng-zorro-antd';
import { ApiService } from '@srvs/api.service';

import { EditCompanyComponent } from './edit-company/edit-company.component';

@Component({
  selector: 'company-management',
  templateUrl: './company-management.component.html'
})
export class CompanyManagementComponent {

  public config: any = {
    loading: false
  };
  public data: any = {
    companies: [],
    companyTotal: 0
  };
  public params: any = {
    pageIndex: 1,
    pageSize: 10,
    lastModifiedTimeSort: null,
    keywords: null
  };
  private debounce: any;

  constructor(
    private modalSrv: NzModalService,
    private msgSrv: NzNotificationService,
    private apiSrv: ApiService
  ) {
    this.load();
  }

  /**
   * 加载公司列表
   * @param pageIndex 页数
   */
  public load(pageIndex?: number): void {
    if (typeof pageIndex === 'number') this.params.pageIndex = pageIndex + 1;

    let apiCompanies: string = '/api/companies';
    const params: any = {
      page: this.params.pageIndex - 1,
      size: this.params.pageSize,
      sort: this.params.lastModifiedTimeSort
        ? `lastModifiedTime,${this.params.lastModifiedTimeSort.slice(0, -3)}`
        : 'id,asc'
    },
      httpOptions: any = {
        observe: 'response'
      };

    if (this.params.keywords) {
      apiCompanies = '/api/_search/companies';
      params.query = `"${this.params.keywords}"`;
    }

    this.config.loading = true;
    this.apiSrv.get(apiCompanies, params, httpOptions)
      .subscribe(
        res => {
          if (!Array.isArray(res.body)) return;
          if (
            res.body.length === 0 &&
            this.params.pageIndex > 1
          ) {
            this.load(this.params.pageIndex - 2);
          } else {
            this.data.companies = res.body;
            this.data.companyTotal = res.headers.get('X-Total-Count');
          }
        },
        error => {
          this.msgSrv.error('公司列表加载失败！', error.message);
          this.config.loading = false;
        },
        () => this.config.loading = false
      );
  }

  /**
   * 创建公司
   */
  public createCompany(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建公司',
      nzContent: EditCompanyComponent,
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditCompanyComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            this.load();
            this.msgSrv.success('创建公司成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建公司失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 修改公司
   * @param company 公司数据
   */
  public updateCompany(company: any): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '修改公司',
      nzContent: EditCompanyComponent,
      nzComponentParams: { data: company },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditCompanyComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const index: number = this.data.companies.indexOf(company),
              companies: any[] = [...this.data.companies];
            companies[index] = data;
            this.data.companies = companies;
            this.msgSrv.success('修改公司成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('修改公司失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 删除公司
   * @param company 公司数据
   */
  public deleteCompany(company: any): void {
    const apiCompany: string = `/api/companies/${company.id}`;
    this.apiSrv.delete(apiCompany).subscribe(
      () => {
        this.load();
        this.msgSrv.success('删除公司成功！', null);
      },
      error => {
        this.msgSrv.error('删除公司失败！', error.message);
      }
    );
  }

  /**
   * 防抖动加载公司数据
   */
  public debounceLoad(): void {
    clearTimeout(this.debounce);
    this.debounce = setTimeout(() => this.load(0), 500);
  }

}
